package config

import (
	"log"
	"os"
	"strconv"
	"time"

	"github.com/joho/godotenv"
)

type Config struct {
    AppEnv       string
    AppHost      string
    AppPort      string
    MySQLDSN     string
    RedisAddr    string
    RedisPassword string
    RedisDB      int
    StorageDir   string
    AuthUsername string
    AuthPassword string
    TokenTTL     time.Duration
    WechatAppID  string
    AlipayAppID  string
}

func Load() (*Config, error) {
	_ = godotenv.Load()

	redisDB, err := strconv.Atoi(getEnv("REDIS_DB", "0"))
	if err != nil {
		return nil, err
	}

	tokenTTL, err := time.ParseDuration(getEnv("AUTH_TOKEN_TTL", "24h"))
	if err != nil {
		log.Printf("invalid AUTH_TOKEN_TTL value, fallback to 24h: %v", err)
		tokenTTL = 24 * time.Hour
	}

    cfg := &Config{
        AppEnv:       getEnv("APP_ENV", "development"),
        AppHost:      getEnv("APP_HOST", "0.0.0.0"),
        AppPort:      getEnv("APP_PORT", "8080"),
        MySQLDSN:     getEnv("MYSQL_DSN", "root:root@tcp(127.0.0.1:3306)/photosales?parseTime=true&loc=Local"),
        RedisAddr:    getEnv("REDIS_ADDR", "localhost:6379"),
        RedisPassword: getEnv("REDIS_PASSWORD", ""),
        RedisDB:      redisDB,
        StorageDir:   getEnv("STORAGE_DIR", "./storage/images"),
        AuthUsername: getEnv("AUTH_USERNAME", "demo"),
        AuthPassword: getEnv("AUTH_PASSWORD", "demo123"),
        TokenTTL:     tokenTTL,
        WechatAppID:  getEnv("WECHAT_APP_ID", ""),
        AlipayAppID:  getEnv("ALIPAY_APP_ID", ""),
    }

	return cfg, nil
}

func getEnv(key, fallback string) string {
	if value, ok := os.LookupEnv(key); ok {
		return value
	}
	return fallback
}
